/*
 * Copyright (c) 2022-2022 All rights Reserved.
 */

package com.driving.core.util;

import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

import org.apache.commons.lang3.StringUtils;

/**
 * 密码加密，解析，验证等工具
 *
 * @author SAGITTAR
 * @since 2017
 */
public class PasswordEncryption {

    private static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";

    /**
     * 生成密文的长度
     */
    private static final int HASH_BIT_SIZE = 512;

    /**
     * 迭代次数
     */
    private static final int PBKDF2_ITERATIONS = 1024;

    private PasswordEncryption() {
        throw new Error();
    }

    /**
     * 对输入的密码进行验证
     *
     * @param attemptedPassword 待验证的密码，明文
     * @param encryptedPassword 密文
     * @return 是否验证成功
     * @throws NoSuchAlgorithmException NoSuchAlgorithm Exception
     * @throws InvalidKeySpecException InvalidKeySpec Exception
     */
    public static boolean authenticate(String attemptedPassword, String encryptedPassword)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 用相同的盐值对用户输入的密码进行加密，把加密后的密文和原密文进行比较，相同则验证成功，否则失败
        return StringUtils.equals(getEncryptedPassword(attemptedPassword), encryptedPassword);
    }

    /**
     * 生成密文
     *
     * @param password 明文密码
     * @return 生成密文
     * @throws NoSuchAlgorithmException NoSuchAlgorithm Exception
     * @throws InvalidKeySpecException InvalidKeySpec Exception
     */
    public static String getEncryptedPassword(String password)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] hex = fromHex(generateSalt());
        KeySpec spec = new PBEKeySpec(password.toCharArray(), hex, PBKDF2_ITERATIONS, HASH_BIT_SIZE);
        SecretKeyFactory f = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
        return toHex(f.generateSecret(spec).getEncoded());
    }

    /**
     * 通过提供加密的强随机数生成器生成盐
     *
     * @return 通过提供加密的强随机数生成器生成盐
     */
    private static String generateSalt() {
        byte[] salt = "Hello World".getBytes();
        return toHex(salt);
    }

    /**
     * 十六进制字符串转二进制字符串
     *
     * @param hex the hex string
     * @return the hex string decoded into a byte array
     */
    private static byte[] fromHex(String hex) {
        byte[] binary = new byte[hex.length() / 2];
        for (int i = 0; i < binary.length; i++) {
            binary[i] = Integer.valueOf(hex.substring(2 * i, 2 * i + 2), 16).byteValue();
        }
        return binary;
    }

    /**
     * 二进制字符串转十六进制字符串
     *
     * @param array the byte array to convert
     * @return a length*2 character string encoding the byte array
     */
    private static String toHex(byte[] array) {
        BigInteger bi = new BigInteger(1, array);
        String hex = bi.toString(16);
        int paddingLength = (array.length * 2) - hex.length();
        return paddingLength > 0 ? String.format("%0" + paddingLength + "d", 0) + hex : hex;
    }
}
